//
//  PaginatorController.swift
//  jocool
//
//  Created by tong on 16/6/6.
//  Copyright © 2016年 zhuxietong. All rights reserved.
//

import UIKit
import Kingfisher
import JoLoading
import Eelay
import Alamofire


open class PaginatorController: TypeInitController,Paginator,TableVConfig {

    open func pageResponse(task: JoTask?, response: RootData?) {
        
    }
    open var sections:TP.section{
        get{
            let sec:TP.section = [
                []
            ]
            return sec
        }
    }
    
    open var selector:TP.selector{
        get{
            let sel = TP.selector()
            assertionFailure("Must override selector:TP.selector,\(#file) \(#line)")
//            alert("Must override selector:TP.selector")
            return sel
        }
    }
    
    public var tableView:UITableView = UITableView(frame: CGRect.zero, style: .plain)
    
    
    public var page_load_section = "section0"
    
    public var contentInsetView: UIScrollView? {
        get{
            return self.tableView
        }
    }
    


    
    required public init() {
        super.init()
    }

    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
 
    
    public func load(sections:TP.section,selector:TP.selector)
    {
        let model =  NSMutableDictionary.TableDictionary(array: (sections as [AnyObject]))
        self.tableView.model =  model
        self.tableView.cell_selector = selector
        //        self.tableView.hidenCellLine()
    }
    
    
    open func layTable(tableView:UIView)
    {
        jo_contentView.eelay = [
            [tableView,[ee.T.L.B.R]],
        ]
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        let vself = self
        vself.pagingScrollView = self.tableView
        self.configTables(tables: tableView)
        layTable(tableView: tableView)
        self.view.backgroundColor = UIColor.white
    
        
    }
    
    open var page_section:Int{
        get{
            let sectionS = self.page_load_section.replacingOccurrences(of: "section", with: "")
            
            return Int(sectionS) ?? 0
        }
    }
    

    open func responesHandle(response:RootData?) {
        
    }
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
        TypeInitController.IDActiveAction(self,actionID,model)
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
    
    
    //一下三个方法与TableConfig中的扩展是一样的
    open func numberOfSections(in tableView: UITableView) -> Int {
        return tableView.sectionCount()
    }
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableView.cellCount(section: section)
    }
    
    @nonobjc open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        
        let cell = tableView.cell(indexPath: indexPath,fillModel: false, owner: self)
        if let jo_cell = cell as? JoTableCell
        {
            jo_cell.mo.controller = self
            jo_cell.mo_theme = mo_theme
            jo_cell.content_controller = self
            jo_cell.delegate = self
            jo_cell.__indexPath = IndexPath(row: indexPath.row, section: indexPath.section)
            
        }
        if let data = tableView.cellData(at: indexPath)
        {
            data.setObject("\(indexPath.row)", forKey: "__row__" as NSCopying)
            data.setObject("\(indexPath.section)", forKey: "__section__" as NSCopying)

            if let mcell = cell as? MoAtrributeProtocol
            {
                mcell.mo.model = data
            }
        }
    
        return cell
    }



    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    open func loadOnePage(list: [Any])->[Any] {
        return list
    }
    
    open func reload_page() {
        loadMore(page: self.paginator.page_begin)//            refresh()
        load(sections: sections, selector: selector)
        tableView.reloadData()
        loadingV.loading()
    }
    
    open override func mo_request_alert
        (
        msg:String = "请检查网络链接是否正常".loc,
        title:String = "".loc,
        bt_title:String = "".loc
        )
    {
        weak var wself = self
        if bt_title.len < 1
        {
            loadingV.show(message: msg, title: title)
            return
        }
        self.loadingV.handle(message: msg, title: title, button: bt_title, handAction: {
            wself?.reload_page()
        })
    }

    
    //注意以下方法override 只能写在
    open func load(page: Int, succeed: Bool, list: [Any], response: RootData?, status: PageDataStatus, scrollView: UIScrollView) {
        if succeed
        {
            if page <= (self.paginator.page_begin + 1)
            {
                loadingV.dismiss(animated: true)
            }
        }
        let _list = self.loadOnePage(list: list)
  
        
        if let tb_view = scrollView as? UITableView
        {
            tb_view.backgroundView = nil
            if succeed
            {
                if let items = tb_view.model[obj:"\(page_load_section)",nil] as? NSMutableArray
                {
                    if page == self.paginator.page_begin
                    {
                        items.removeAllObjects()
                        loadingV.dismiss(animated: true)
                    }
                    
                    items.addObjects(from: _list)
//                    if items.count < 1
//                    {
//                        if let leb = self.backMsgView as? UILabel
//                        {
//                            _ = leb.ui.font17.cl_888
//                            leb.text = self.paginator.empty_msg
//                        }
//                    }
//                    if end
//                    {
//                        if let leb = self.backMsgView as? UILabel
//                        {
//                            _ = leb.ui.font17.cl_888
//                            leb.text = self.paginator.empty_msg
//                        }
//
//                    }
                    switch status{
                    case .empty:
                        tb_view.backgroundView = emptyLayer
                        emptyLayer.emptyMessage = paginator.empty_msg
                       
                    case .err(let msg):
                        print("loadListErr|\(msg)")
                    default:
                        break
                    }
                
                    
                    self.responesHandle(response: response)
                    tb_view.reloadData()
                }
            }
            else{
                if page == self.paginator.page_begin
                {
                    
//                    self.mo_request_alert(msg: status.message)
                    self.loadingV.alertResult(result: self.paginator.net.resultTip)


//                    else{
//                        if let leb = self.backMsgView as? UILabel
//                        {
//                            leb.text = msg
//                        }
//                    }

                }
            }
            
        }
    }
    
    deinit {
        self.paginator.net.cancel()
        if TypeInitController.autoClearMemoryCache
        {
            KingfisherManager.shared.cache.clearMemoryCache()
        }
        
    }
    
    
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
}




